﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DiskClearHelper
{
    /// <summary>
    /// EntryInfoControl.xaml 的交互逻辑
    /// </summary>
    public partial class EntryInfoControl : UserControl
    {
        public EntryInfoControl()
        {
            InitializeComponent();

            this.DataContext = this;
        }

        public async Task SetRootPath(string rootPath,long totalSize)
        {
            txtPath.Text = rootPath;
            List<EntryInfo> entryInfos = await ListCurrentFilesAndFoldersAsync(rootPath);
            for (int i = 0; i < entryInfos.Count; i++)
            {
                entryInfos[i].ParentSzie = totalSize;
            }
            lvEntry.ItemsSource = entryInfos;
        }

        private async Task<List<EntryInfo>> ListCurrentFilesAndFoldersAsync(string rootPath)
        {
            List<EntryInfo> ret = await Task.Run(() =>
            {
                var items = ListCurrentFilesAndFolders(rootPath);
                foreach (var item in items)
                {
                    var dval = item.TotalSize;
                }
                return items;
            });
            return ret;
        }

        private static Dictionary<string, EntryInfo> _sizeDic = new Dictionary<string, EntryInfo>();

        private static EntryInfo CreateEntryInfo(string name,EntryType entry)
        {
            if(!_sizeDic.ContainsKey(name))
            {
                _sizeDic[name] = new EntryInfo();
                _sizeDic[name].Name = name;
                _sizeDic[name].EntryType = entry;
            }
            return _sizeDic[name];
        }

        private List<EntryInfo> ListCurrentFilesAndFolders(string directoryPath)
        {
            List<EntryInfo> ret = new List<EntryInfo>();
            try
            {
                // 获取当前目录的文件夹
                string[] directories = Directory.GetDirectories(directoryPath);

                foreach (string d in directories)
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(d);

                    if (directoryInfo.Attributes.HasFlag(FileAttributes.System))
                    {
                        continue;
                    }
                    EntryInfo info = CreateEntryInfo(d, EntryType.Directory);
                    ret.Add(info);
                }

                // 获取当前目录的文件
                string[] files = Directory.GetFiles(directoryPath);
                foreach (string f in files)
                {
                    FileInfo fileInfo = new FileInfo(f);
                    if (fileInfo.Attributes.HasFlag(FileAttributes.System))
                    {
                        continue;
                    }
                    EntryInfo info = CreateEntryInfo(f, EntryType.File);
                    ret.Add(info);
                }
            }
            catch (UnauthorizedAccessException)
            {
                Console.WriteLine($"无权限访问: {directoryPath}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理目录 {directoryPath} 时发生错误: {ex.Message}");
            }

            return ret;
        }

        private void lvEntry_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private async void miAnalysis_Click(object sender, RoutedEventArgs e)
        {
            if (lvEntry.SelectedItem is EntryInfo selectedItem)
            {
                await SetRootPath(selectedItem.Name, selectedItem.TotalSize);
            }
        }

        private void miOpenDir_Click(object sender, RoutedEventArgs e)
        {
            if ((lvEntry.SelectedItem is EntryInfo selectedItem) &&
                selectedItem.EntryType == EntryType.Directory)
            {
                    // 打开文件夹
                    System.Diagnostics.Process.Start("explorer.exe", selectedItem.Name);
            }
        }

        private async void btnUpper_Click(object sender, RoutedEventArgs e)
        {
            if(txtPath.Text==string.Empty)
            {
                return;
            }

            DirectoryInfo parent = new DirectoryInfo(txtPath.Text).Parent;

            if (parent != null)
            {
                string parentName = parent.FullName;
                if(_sizeDic.ContainsKey(parentName))
                {
                    await SetRootPath(parentName, _sizeDic[parentName].TotalSize);
                }
                else
                {
                    long size = new DriveInfo(parentName).TotalSize;
                    await SetRootPath(parentName, size);
                }
            }
        }
    }
}
